<template>
  <div>
    <!-- 轮播图 -->
    <swiper indicator-dots>
      <block v-for="(item, index) in detail.pics" :key="index">
        <swiper-item>
          <image
            :src="item.pics_big_url"
            mode="aspectFill"
            class="slide-image"
          ></image>
        </swiper-item>
      </block>
    </swiper>
    <!-- 商品基本信息 -->
    <div class="goods-info">
      <div class="goods-price">￥{{ detail.goods_price }}</div>
      <div class="goods-title">
        <h4>{{ detail.goods_name }}</h4>
        <div class="goods-star">
          <span class="iconfont icon-shoucang"></span>
          <p>分享</p>
          <button open-type="share" class="share-btn">分享</button>
        </div>
      </div>
    </div>
    <!-- 商品详细信息 -->
    <div class="goods-detail">
      <div class="goods-detail-title">商品详情</div>
      <div v-html="detail.goods_introduce"></div>
    </div>
    <!-- 底部菜单 -->
    <div class="footer">
      <button class="contact"></button>
      <div class="footer-left">
        <span class="iconfont icon-kefu"></span>
        <p>联系客服</p>
      </div>
      <navigator
        url="/pages/cart/main"
        open-type="switchTab"
        class="footer-left"
      >
        <span class="iconfont icon-gouwuche"></span>
        <p>购物车</p>
      </navigator>
      <div @click="addCart" class="footer-right">加购物车</div>
      <div @click="toBuy" class="footer-right">立即购买</div>
    </div>
  </div>
</template>

<script>
import request from "../../utils/request";
export default {
  data() {
    return {
      goodsId: "",
      detail: {},
    };
  },
  onLoad(param) {
    console.log(param);
    this.goodsId = param.gid;
    this.initData();
  },
  methods: {
    toBuy() {
      // 去购买：先添加购物车，再跳转到购物车页面
      this.addCart();
      // 跳转到购物车页面
      mpvue.switchTab({
        url: "/pages/cart/main",
      });
    },
    addCart() {
      // 加入购物车
      // 先查询购物车中是否有商品
      let cart = mpvue.getStorageSync("mycart") || {};
      // 默认购买一件商品
      if (cart[this.goodsId]) {
        // 如果购物车已经存同样的商品，就在原有的数量上加1
        cart[this.goodsId].num = cart[this.goodsId].num + 1;
      } else {
        // 把商品加入购物车
        cart[this.goodsId] = this.detail;
        // 商品选中与否的控制
        cart[this.goodsId].checked = false;
        // 第一次购买的商品
        cart[this.goodsId].num = 1;
      }

      console.log(cart[this.goodsId].num);
      // 把购物车的数据保存在本地缓存中
      mpvue.setStorageSync("mycart", cart);
      console.log(cart);
      mpvue.showToast({
        title: "商品添加成功",
        icon: "success",
      });
    },
    async initData() {
      // 根据商品的id查询详细信息
      const res = await request("goods/detail", { goods_id: this.goodsId });
      //   console.log(res);
      this.detail = res.data.message;
    },
  },
};
</script>

<style lang="less" scoped>
@import "./main.less";
</style>
